package com.hontech.kaltaapp.ui.parts

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import com.hontech.kaltaapp.R
import com.hontech.kaltaapp.device.drawHeatCtrl
import com.hontech.kaltaapp.device.event.DeviceStatus
import com.hontech.kaltaapp.ui.dialog.showErr
import com.hontech.kaltaapp.ui.view.LabelSpinner
import com.hontech.kaltaapp.ui.view.LabelTextView
import com.hontech.kaltaapp.utils.register
import com.hontech.kaltaapp.utils.runOnUi
import com.hontech.kaltaapp.utils.unregister
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class DrawHeatInfoParts (context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    private val ltSteamTemp: LabelTextView
    private val ltWaterTemp: LabelTextView
    private val ltFlow: LabelTextView
    private val ltKpa: LabelTextView
    private val ltDraw: LabelTextView
    private val ltSteam: LabelTextView
    private val ltWater: LabelTextView

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.parts_draw_heat_info, this)
        ltSteamTemp = view.findViewById(R.id.id_draw_heat_lt_steam_temp)
        ltWaterTemp = view.findViewById(R.id.id_draw_heat_lt_water_temp)
        ltFlow = view.findViewById(R.id.id_draw_heat_lt_flow)
        ltKpa = view.findViewById(R.id.id_draw_heat_lt_kpa)
        ltDraw = view.findViewById(R.id.id_draw_heat_lt_draw_info)
        ltSteam = view.findViewById(R.id.id_draw_heat_lt_steam_info)
        ltWater = view.findViewById(R.id.id_draw_heat_lt_water_info)

        val sp = view.findViewById<LabelSpinner>(R.id.id_draw_heat_lsp_ctrl)
        sp.setSelectFunc { _, index ->
            runOnUi {
                try {
                    drawHeatCtrl(index)
                } catch (e: Exception) {
                    showErr("错误", e)
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onStatusUpdate(status: DeviceStatus) {
        ltSteamTemp.set("${status.steam.value}℃")
        ltWaterTemp.set("${status.water.value}℃")
        ltKpa.set("${status.kpa}kpa")
        ltDraw.set(status.drawInfo)
        ltSteam.set(status.steamInfo)
        ltWater.set(status.waterInfo)
        ltFlow.set(status.flow)
    }

    override fun onWindowVisibilityChanged(visibility: Int) {
        super.onWindowVisibilityChanged(visibility)
        if (visibility == VISIBLE) {
            register(this)
        } else {
            unregister(this)
        }
    }
}